const { ipcMain, app, BrowserWindow, Notification, Tray, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const request = require('request');
const compareVersions = require('compare-versions');
const userDataPath = app.getPath("userData");
const LocalStorage = require('node-localstorage').LocalStorage;
const localStorage= new LocalStorage(path.join(userDataPath,"setting.db"));
let remindStyle = 0;// 0 - flicker ; 1 - show jenkins-msg.ico
///////////////////////////////////////////////////////

function MonitorWindow(debug = false) {
    var trayFlickerID = 0;
    let tray;
    var mainWindow;
    var settingWindow;
    var aboutWindow;
    var isOntop = false;
    // let tray flicker
    function trayFlicker() {
        var count = 0;
        stopTrayFlicker();
        if(remindStyle == 1) {
            tray.setImage(path.join(__dirname, '../res/jenkins-msg.ico'));
        }
        else {
            trayFlickerID = setInterval(function () {
                if (count++ % 2 == 0) {
                    tray.setImage(path.join(__dirname, '../res/favicon.ico'));
                } else {
                    tray.setImage(path.join(__dirname, '../res/empty.ico'));
                }
            }, 400);
        }
        // tray.displayBalloon({
        //     title:"hit",
        //     content: "hello world"
        // });
    }
    function stopTrayFlicker() {
        tray.setImage(path.join(__dirname, '../res/favicon.ico'));
        if (trayFlickerID == 0) {
            return;
        }
        clearInterval(trayFlickerID);
        trayFlickerID = 0;
    };
    // set attr
    this.setAboutWindow = function(win) {
        aboutWindow = win;
    };
    this.setSettingWindow = function(win) {
        settingWindow = win;
    }

    this.createWindow = function () {
        Menu.setApplicationMenu(null);
        
        mainWindow = new BrowserWindow({
            width: 300,
            height: 400,
            webPreferences: {
                nodeIntegration: true,
                defaultFontFamily: {
                    standard:"WenQuanYi Micro Hei",
                }
            },
            frame: false,
            resizable: false,
            minHeight: 0,
            minWidth: 0,
            maxHeight: 40000,
            maxWidth: 4000,
            backgroundColor: "#80DCDCDC",
            transparent: true,
        })
        mainWindow.setSkipTaskbar(true);
        mainWindow.loadURL(path.join(__dirname, '../html/index.html'))
        mainWindow.on('closed', function () {
            mainWindow = null;
        });
        mainWindow.on("focus", () => {
            stopTrayFlicker();
        });

        //for debug
        if (debug) {
            mainWindow.webContents.openDevTools();
            mainWindow.maximize();
        }
        tray = new Tray(path.join(__dirname, '../res/favicon.ico'))
        //系统托盘右键菜单
        var trayMenuTemplate = [
            {
                id: "0",
                label: 'Setting',
                click: function () {
                    settingWindow.createWindow();
                }
            },
            {
                id: "1",
                type: "checkbox",
                label: 'Always on top',
                click: function () {
                    isOntop = !isOntop;
                    mainWindow.setAlwaysOnTop(isOntop);
                    localStorage.setItem("isOntop", isOntop ? "true" : "false");
                    mainWindow.show();
                }
            },
            {
                id: "2",
                label: 'Hide window',
                click: function () {
                    mainWindow.hide();
                }
            },
            //////////////////////////////////////////
            {
                id: "3",
                label: 'About',
                click: function () {
                    aboutWindow.createWindow();
                }
            },
            {
                id: "4",
                label: 'Exit',
                click: function () {
                    //ipc.send('close-main-window');
                    app.quit();
                }
            }
        ];
        const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
        tray.setToolTip('小工具');
        tray.setContextMenu(contextMenu);
        tray.on('click', function(){
            stopTrayFlicker();
            mainWindow.show();
        }.bind(this));

        // init setting
        if (localStorage.getItem("isOntop") == "true") {
            mainWindow.setAlwaysOnTop(true);
            isOntop = true;
            contextMenu.getMenuItemById("1").checked = true;
        }

        // this is ipc
        ipcMain.on('system', function (event, data) {
            event;
            if (data == "trayflickerStart") {
                trayFlicker();
            }
            else if (data == "reload") {
                mainWindow.reload();
            }
        });
        ipcMain.on("setWidth", function(event, data){
            var size = JSON.parse(data);
            if(!debug) {
                mainWindow.setBounds(size);
            }
        });
        ipcMain.on("setMsgStyle",function(event, data){
            remindStyle = parseInt(data);
            event.returnValue = "PONG";
        });
        return mainWindow;
    };
    this.show = function() {
        mainWindow.show();
    };
    this.focus = function() {
        mainWindow.focus();
    };
    this.stopTrayFlicker = function() {
        stopTrayFlicker();
    };
}

// Version check and update
// once a day
var packageJson = require(path.join(__dirname, "../package.json"));
setTimeout(updateVersion, 5000);
setInterval(updateVersion, 1000 * 60 * 60 * 24);
var isIgnore = false;
function updateVersion() {
    if(isIgnore) {
        return;
    }
    var url = packageJson.serverUrl;
    request.get(url + "/getVersion.json", function (error, response, body) {
        try {
            var data = JSON.parse(body);
            if (compareVersions(data.version, packageJson.version) == 1) {
                var updateWindow = new BrowserWindow({
                    webPreferences: {
                        nodeIntegration: true,
                        defaultFontFamily: {
                            standard: "WenQuanYi Micro Hei",
                        }
                    }
                });
                updateWindow.loadFile(path.join(__dirname, '../html/update.html'));
                updateWindow.webContents.on('did-finish-load', () => {
                    updateWindow.webContents.send("assign", body);
                });
                ipcMain.on("ignoreUpdate",function(event, data){
                    updateWindow.close();
                    isIgnore = true;
                });
            }
        }
        catch (e) {
            console.log("error");
        }
    });
}

module.exports = MonitorWindow;